<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <div class="app-container" style="display: flex;">
      <el-row :span="24" :gutter="10">
        <el-col :span="6">
          <el-card class="box-card">
            <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch"
                     label-width="98px">
              <el-form-item label="产品名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入产品名称" style="width: 150px;"
                          clearable @keyup.enter.native="handleQuery"/>
              </el-form-item>
              <el-form-item label="产品型号" prop="model">
                <el-input v-model="queryParams.model" placeholder="请输入产品型号" style="width: 150px;"
                          clearable @keyup.enter.native="handleQuery"/>
              </el-form-item>
              <el-form-item label="产品明细" prop="brand">
                <el-input v-model="queryParams.brand" placeholder="请输入产品明细" style="width: 150px;"
                          clearable @keyup.enter.native="handleQuery"/>
              </el-form-item>
              <div style=" display: flex;align-items: center;">
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <el-button type="info" icon="el-icon-upload2" size="mini" @click="showUploadDialog">导 入</el-button>
              </div>
              <div style="display: flex;align-items: center;margin-top: 30px;">

                <el-input-number v-model="form.counts"></el-input-number>

                <el-button type="primary" size="mini" @click="submitFormBuy">添 加</el-button>
              </div>
            </el-form>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-card class="box-card" style="margin-left: 10px;">
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
              <el-table border v-loading="loading" :data="columns" @selection-change="handleSelectionChange"
                        :max-height="400">
                <el-table-column type="selection" width="55" align="center"/>
                <el-table-column label="商品编码" align="center" prop="code"/>
                <el-table-column label="商品名称" align="center" prop="name"/>
                <!-- <el-table-column label="商品品牌" align="center" prop="brand"/>-->
                <el-table-column label="商品型号" align="center" prop="model"/>
                <el-table-column label="商品明细" align="center" prop="brand"/>
                <el-table-column label="商品单位" align="center" prop="unit"/>
                <el-table-column label="含税单价(成本)" align="center" prop="costPriceTax"/>
                <!--<el-table-column label="销售单价(成本)" width="210">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.costPriceTax" :precision="2"
                                     :min="0"></el-input-number>
                  </template>
                </el-table-column>-->
                <!-- <el-table-column label="订单数量" align="center" prop="counts" width="210">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.counts"
                                       :min="0" ></el-input-number>
                    </template>
                  </el-table-column>-->
                <!-- <el-table-column label="采购数量" align="center" prop="count"/> -->
                <el-table-column label="库存数量" align="center" prop="remainderCount"/>
                <el-table-column label="销售单价" align="center" prop="goodsUnitPrice"/>
                <!--   <el-table-column label="销售单价" width="210">
                     <template slot-scope="scope">
                       <el-input-number v-model="scope.row.goodsUnitPrice" :precision="2"
                                        :min="scope.row.costPriceTax" @change="handleChangeMoney(scope.row)"></el-input-number>
                     </template>
                   </el-table-column>-->
                <el-table-column label="使用数量" width="210">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.goodsCount" :max="scope.row.remainderCount"
                                     :min="0" @change="handleChangeMoney(scope.row)"></el-input-number>
                  </template>
                </el-table-column>
                <!--  <el-table-column label="采购数量" width="210">
                    <template slot-scope="scope">
                      <el-input-number v-model="scope.row.buyCount" :max="scope.row.buyCount" :min="0" ></el-input-number>
                    </template>
                  </el-table-column>-->
                <!--<el-table-column label="销售总价" width="210">
                  <template slot-scope="scope">
                    <el-input-number disabled v-model="scope.row.goodsTotalPrice" :min="0"></el-input-number>
                  </template>
                </el-table-column>-->
                <el-table-column label="销售总价" align="center" prop="goodsTotalPrice"/>

                <!--<el-table-column label="剩余数量" width="210">
                   <template slot-scope="scope">
                     <el-input-number disabled v-model="scope.row.shengyu" :min="0"></el-input-number>
                   </template>
                 </el-table-column>-->
                <el-table-column label="发生日期" width="200">
                  <template slot-scope="scope">
                    <el-date-picker clearable style="width: 160px"
                                    v-model="scope.row.buyDate"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择发生日期">
                    </el-date-picker>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
            <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @pagination="getList"/>
          </el-card>
        </el-col>
      </el-row>
    </div>
        <el-card class="box-card">
          <el-table :data="columns2" ref="dragTable" row-key="id" v-loading="loading2">
            <el-table-column align="center" label="序号" type="index" width="50">
              <template slot-scope="scope">
                <span>{{ (queryParams2.pageNum - 1) * queryParams2.pageSize + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="商品编码" align="center" prop="code"/>
            <el-table-column align="center" label="商品名称" prop="goodsName"/>
            <!--<el-table-column align="center" label="商品品牌" prop="brand"/>-->
            <el-table-column align="center" label="产品型号" prop="goodModel"/>
           <!-- <el-table-column align="center" label="型号明细" prop="goodsBrand"/>-->
            <el-table-column align="center" label="商品单位" prop="unit"/>
            <!--<el-table-column align="center" label="含税单价(成本)" prop="costPriceTax"/>-->
            <!--      <el-table-column label="采购数量" align="center" prop="count"/>-->
            <!--      <el-table-column label="库存数量" align="center" prop="remainderCount"/>-->
            <el-table-column align="center" label="销售单价" prop="goodsUnitPrice"/>
            <el-table-column align="center" label="订单数量" prop="counts"/>
            <el-table-column align="center" label="锁定数量" prop="goodsCount"/>
            <el-table-column align="center" label="请购数量" prop="shengyu"/>
            <el-table-column align="center" label="销售总价" prop="goodsTotalPrice"/>
            <el-table-column align="center" label="销售成本" prop="goodsBuyTotal"/>
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
              <template slot-scope="scope">
                <el-popconfirm :title="`确认删除 `+scope.row.goodsName+` 数据项？`" @confirm="handleDelete(scope.row)"
                               style="margin-left: 10px;">
                  <el-button icon="el-icon-delete" size="mini" slot="reference" type="text">删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>


    <div slot="footer" class="dialog-footer">
      <!--<el-button type="primary" @click="submitScalado" v-if="">提交请购</el-button>-->
      <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
      <el-button @click="cancel">取 消</el-button>
    </div>
    <upload-dialog ref="uploadDialog" @ok="getList2" @handleFileSuccess="handleFileSuccess"></upload-dialog>

  </el-dialog>
</template>

<script>
import UploadDialog from "@/views/upload/UploadDialog";
import {addAction, deleteAction, getAction, getById, updateAction} from '@/api/manage'
import {insertGoodsSale} from '@/api/develop/goodsSale'
// import { updateGoodsSale } from '@/api/develop/goodsProject'
export default {
  name: "GoodsBuyChose",
  dicts: ['goods_customer', 'company', 'yes_no', 'buy_type'],
  components: {
    UploadDialog
  },
  data() {
    return {
      proId: '',
      ironRecordId: '',
      // 遮罩层
      title: "产品选择",
      loading: false,
      open: false,
      // 选中数组
      ids: [],
      proStatus: "",
      saleType: "2",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库信息管理表格数据
      dataList: [],
      columns: [],
      form: {
        counts: null,
      },
      rules: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        model: null,
        brand: null,
        unit: null,
        costPrice: null,
        count: null,
        cost: null,
        validityTerm: null,
        buyId: null,
        buyName: null,
        buyDate: null,
        buyType: null,
        reimburse: null,
        supplierId: null,
        supplierName: null,
        params: {
          dataFlag: "1"
        }
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 1000,
        id: null,
        name: null,
        model: null,
        brand: null,
        taxNo: null,
        addr: null,
        tel: null,
        bankName: null,
        bankNo: null,
        info: null,
        status: "2",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        type: "其他"
      },
      total2: '',
      loading2: '',
      columns2: [],
      url: {
        list: '/goodsOrderIn/goodsOrderIn/list',
        remove: '/goodsOrderIn/goodsOrderIn/',
        export: '/goodsOrderIn/goodsOrderIn/export',
        insertForPrjDo: '/goodsSale/goodsSale/insertForPrjDo',
        list2: '/goodsSale/goodsSale/listSaleProject',
        remove2: '/goodsSaledo/goodsSaledo/deleteProject/',
        submitScalado: '/goodsSaledo/goodsSaledo/submitScalado',
        listDo: '/goodsSaledo/goodsSaledo/listSaleProject',

      },
      tableMaxHeight: window.innerHeight - 900,
    };
  },
  created() {

  },
  methods: {
    handleFileSuccess(response, file, fileList) {
      this.$refs.uploadDialog.open = false;
      this.$refs.uploadDialog.isUploading = false;
      if (response.data.code == "200") {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
      } else {
        this.$alert("导入数据：" + response.data.num + "条！更新数据：" + response.data.numupdate + "条！" + response.data.errorText, "导入结果", {dangerouslyUseHTMLString: true});
      }
      this.getList2();
    },
    showUploadDialog() {
      this.$refs.uploadDialog.title = "信息导入";
      this.$refs.uploadDialog.tmplName = "订单信息模板.xlsx";
      this.$refs.uploadDialog.fileName = "订单信息.xlsx";
      this.$refs.uploadDialog.uploadUrl = "/projectBaseInfo/projectBaseInfo/importData";
      this.$refs.uploadDialog.show();
    },
    getList2() {
      this.loading2 = true;
      /*getById(this.url.listBatch, this.ids).then(response => {
        this.columns = response.rows;
        this.total = response.total;
        this.loading = false;
      });*/
      this.queryParams2.projectId = this.proId
      getAction(this.url.listDo, this.queryParams2).then(response => {
        this.columns2 = response.rows;
        this.total2 = response.total;
        this.loading2 = false;
      });
    },
    handleUpdate(row) {
      const id = row.id || this.ids;
      this.proId = id;
      this.open = true;
      this.loading = false;
      this.proStatus = row.status;
      // this.chose(this.proId, "2");
      this.getList2();
    },
    refreshPageData() {
      let that = this;
      let param = {
        id: that.proId
      }
      that.handleUpdate(param);

    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove2, ids).then(response => {
        this.refreshPageData();
        this.$modal.msgSuccess("删除成功");
        this.handleQuery();
      }).catch(() => {
      });
    },
    // handleChangeCounts(row) {
    //   let that = this;
    //   let handleReckonMoney = (row) => {
    //     if(row.shengyu ==undefined || row.shengyu ==null ){
    //       let row_count = 0;
    //       row_count =row.counts- row.goodsCount;
    //       that.$set(row, 'shengyu', row_count);
    //     }else{
    //       let row_count =row.shengyu- row.goodsCount;
    //       that.$set(row, 'counts', row_count);
    //     }
    //   };
    //   handleReckonMoney(row);
    // },
    handleChangeMoney(row) {
      let that = this;
      let handleReckonMoney = (row) => {
        let row_money = 0;
        row_money = that.functionNumberMul(Number(row.goodsUnitPrice), Number(row.goodsCount))
        that.$set(row, 'goodsTotalPrice', row_money);
      };
      handleReckonMoney(row);
    },
    functionNumberMul(arg1, arg2) {
      var m = 0;
      var s1 = arg1.toString();
      var s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) {
      }
      try {
        m += s2.split(".")[1].length;
      } catch (e) {
      }
      return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    },
    chose(proId, type) {
      this.open = true;
      this.proId = proId;
      this.saleType = type;
      this.getList2();
    },
    choseByIronRecord(ironRecordId, proId, type) {
      this.open = true;
      this.proId = proId;
      this.ironRecordId = ironRecordId;
      this.queryParams2.type = type;
      this.saleType = type;
      this.getList2();
    },
    getList() {
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        let res = response.rows;
        for (let i = 0; i < res.length; i++) {
          res[i].buyDate = new Date();
        }
        this.columns = res;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // this.reset();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.dataList = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    submitScalado() {
      let that = this;
      if (that.columns2.length > 0) {
        const goodsOrderIn = Object.assign({});
        goodsOrderIn.projectId = that.proId;
        goodsOrderIn.type = "其他";
        goodsOrderIn.status = "22";
        goodsOrderIn.columns = that.columns2;
        addAction(this.url.submitScalado, goodsOrderIn).then(response => {
          this.refreshPageData();
          this.$modal.msgSuccess("提交请购成功!");
          this.open = false;
          this.handleQuery();
        }).catch(() => {
        });

      } else {
        alert("没有可请购产品，请选择产品后再次提交！");
      }
    },
    /** 提交按钮 */
    submitFormBuy() {
      let that = this;
      if (that.form.counts && that.form.counts >= 0) {
        const ids = this.ids;
        if (ids == null || ids == '' || ids == 'undefined') {
          that.$modal.msgError("请选择一条记录");
          // alert("请选择一条记录");
        } else {
          that.$refs["form"].validate(valid => {
            if (valid) {
              const goodsOrderIn = Object.assign({});
              goodsOrderIn.projectId = that.proId;
              goodsOrderIn.type = that.saleType;
              goodsOrderIn.counts = that.form.counts;
              //goodsOrderIn.ids=ids.toString();
              goodsOrderIn.columnsDo = that.dataList;
              addAction(that.url.insertForPrjDo, goodsOrderIn).then(response => {
                that.$modal.msgSuccess("添加成功");
                // this.open = false;
                that.$emit('ok');
                // this.queryParams2.pageNum = 1
                // this.queryParams2.pageSize = 1000
                that.getList2();
                that.handleQuery();
              });
              /*insertGoodsSale(goodsOrderIn).then(res => {
                that.$modal.msgSuccess(res.msg);
                if (res.code === 200) {
                  that.$modal.msgSuccess("修改完成！");
                  that.open = false;
                  that.$emit('ok');
                }
              });*/
            }
          });
          /*const goodsOrderIn = Object.assign({});
          goodsOrderIn.projectId = this.proId;
          goodsOrderIn.ids=ids.toString();
          insertGoodsSale(goodsOrderIn).then(res => {
            if (res.code === 200) {
              this.open = false;
              this.$emit('ok');
            }
          });*/
        }
      } else {
        alert("请填写该订单的请购数量！");
      }

    },
  }
};
</script>
